package com.vertxsample.samples.helloworld

import io.vertx.core.AbstractVerticle
import io.vertx.core.Vertx
import io.vertx.core.http.HttpServerResponse
import io.vertx.core.json.Json
import io.vertx.ext.web.Router

class App : AbstractVerticle() {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            val vertx = Vertx.vertx()

            vertx.deployVerticle(App())
        }
    }
    override fun start() {
        var router = customRouter(vertx)
        println("server running on 8888")
        vertx.createHttpServer().requestHandler({ handler -> router.handle(handler)}).listen(8888)
    }
    fun customRouter(vertx : Vertx) : Router {
        var router = Router.router(vertx)

        // http://localhost:8888   ->   hello world
        // http://localhost:8888/json  -> {"name":"name","description":"sss"}

        router.route("/").handler({c -> c.response().html().end("hello world")})
        router.route("/json").handler({c -> c.response().json().end(Json.encode(Entity("name","sss")))})
        return router
    }

    fun HttpServerResponse.html() : HttpServerResponse {
        return this.putHeader("content-type","text/html")
    }

    fun HttpServerResponse.json() : HttpServerResponse {
        return this.putHeader("content-type","application/json; charset=utf-8")
    }
}
data class Entity(var name:String,var description:String){}